<?php

namespace App\Models\Traits;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

trait HasCovers
{
    /**
     * Notes   : 对使用该trait的模型进行初始化，设置状态字段类型
     *
     * @Date   : 2023/11/6 15:14
     * @Author : <Jason.C>
     */
    public function initializeHasCovers(): void
    {
        if (!isset($this->casts[$this->getPicturesField()])) {
            $this->casts[$this->getPicturesField()] = 'json';
        }
    }

    protected function getPicturesField(): string
    {
        if (property_exists($this, 'picturesField')) {
            return $this->getPicturesField();
        }

        return 'pictures';
    }

    public function coverUrl(): Attribute
    {
        return new Attribute(
            get: fn() => $this->parseImageUrl($this->getAttribute($this->getCoverField()))
        );
    }

    public function parseImageUrl(?string $image): string
    {
        if (empty($image)) {
            return '';
        } elseif (Str::startsWith($image, 'http')) {
            return $image;
        } else {
            return Storage::url($image);
        }
    }

    protected function getCoverField(): string
    {
        if (property_exists($this, 'coverField')) {
            return $this->getCoverField();
        }

        return 'cover';
    }

    public function pictureUrls(): Attribute
    {
        return new Attribute(
            get: function () {
                $pictures = $this->getAttribute($this->getPicturesField());
                if (empty($pictures)) {
                    return [];
                }

                return collect($pictures)->map(function ($picture) {
                    return $this->parseImageUrl($picture);
                })->toArray();
            }
        );
    }
}
